/**
 * Created by 功振 on 2016/2/22.
 */
angular.module('NatureCloud').factory('k8sService', function ($http) {

    function  applyMe(k8sService,params,promise ) {
        return k8sService.checkIfResExceedLimit( params.data,params.status,params.replicas,params.op ).then(function (r) { //resolve
            if(r.data == true){//rc 设置成功
                //console.log("checkIfResExceedLimit#success:"+ JSON.stringify( promise ) ) ;
                params.limitCheck = "yes" ;//skip the second limit check
                return promise( params ) ;
            }else{
                console.log( "checkIfResExceedLimit#fail:"+JSON.stringify( r.data )) ;
                return {
                    "data": r.data
                } ;
            }
        }, function (r) {//reject
            console.log( "checkIfResExceedLimit#exception:"+JSON.stringify( r )) ;
            return {
                "data":"用户资源检测失败！"
            } ;
        });
    }

    return {
        createNamespace: function (user) {
            var namespaceInfo = {
                kind: "Namespace",
                apiVersion: "v1",
                metadata: {
                    name: user
                }
            }

            return $http.post('/apiKube/api/v1/namespaces', namespaceInfo).then(function (response) {
                return response;
            });
        },
        grayupdate:function(svc,newversion){
            var grayupdInfo = {
                data: svc,
                ver: newversion
            }
            return $http.post('/apiApplication/grayudp', grayupdInfo).then(function (response) {
                if( response && response.data ){
                    var result = response.data ;
                    if( result.ret ){
                        result.status =  result.status||200 ;
                        return result ;
                    }
                    throw result ;
                }
                return response;
            });
        },
        modifyReplicas:function(svc,scale_num){
            var data = {
                data:svc,
                status:"running",
                replicas:scale_num,
                op:'modifyReplicas'
            }
            return applyMe( this ,data , function(data01){
                return $http.post('/apiApplication/modifyRc', data01).then(function (response) {
                    if( response && response.data){
                        var result = response.data ;
                        if( result.ret ){
                            result.status =  result.status||200 ;
                            return result ;
                        }
                        throw result ;
                    }
                    return response;
                })
            } ) ;
                // return $http.post('/apiApplication/modifyRc', data).then(function (response) {
                //     return response;
                // });
        },
        startService:function(svc){
            // var data = {
            //     data:svc,
            //     replicas:svc.rcnum,
            //     op:'start'
            // }
            // return $http.post('/apiApplication/modifyRc', data).then(function (response) {
            //     return response;
            // });
            //----------------------since 2016/9/28
            //check the resource first
            var data = {
                data:svc,
                status:"running",
                replicas:svc.rcnum,
                op:'start'
            }
            return applyMe( this ,data , function(data01){
                //sub method
                return $http.post('/apiApplication/modifyRc', data01).then(function (response) {
                    if( response && response.data){
                        var result = response.data ;
                        if( result.ret ){
                            result.status =  result.status||200 ;
                            return result ;
                        }
                        throw result ;
                    }
                    return response;
                })
            } ) ;

        },
        /**
         * 停止服务，设置rc.replicas=0
         * @returns {*}
         */
        stopService:function(svc,force){
            //stopping don't need check resource quota
            var data = {
                data:svc,
                replicas:0,
                limitCheck:'yes',
                forceDelete:force
            }
            return $http.post('/apiApplication/modifyRc', data).then(function (response) {
                if( response && response.data){
                    var result = response.data ;
                    if( result.ret ){
                        result.status =  result.status||200 ;
                        return result ;
                    }
                    throw result ;
                }
                return response;
            });
        },
        getpodStatus:function(svc){
            /*var data = {
                app:svc.app
            }*/
            return $http.post('/apiApplication/getPodStatus', svc).then(function (response) {
                if( response && response.data ){
                    var result = response.data ;
                    if( result.ret ){
                        result.status =  result.status||200 ;
                        return result ;
                    }else{
                        console.log("error "+ result.error ) ;
                        throw result ;
                    }
                }
                return response;
            });
        },
        getRcStatus:function(svc){
            /*var data = {
             app:svc.app
             }*/
            return $http.post('/apiApplication/getRcSimple', svc).then(function (response) {
                return response;
            });
        },
        getpodByName:function(param){
            var data = {
                clusterId:param.clusterId,
                item:param.item
             }
            return $http.post('/apiApplication/getPodByName', data).then(function (response) {
                return response;
            });
        },
        getDefaultPodStatus:function(svc){
            /*var data = {
                app:svc.app
            }*/
            return $http.post('/apiApplication/getDefaultPodStatus', svc).then(function (response) {
                return response;
            });
        },
        getpodStatusPromise:function(svc,evt){
            //TODO clear the no-used method and specify the standard parameter and result format
            /*var data = {
                app:svc.app
            }*/
            if(evt !== undefined){
                evt.promise = $http.post('/apiApplication/getPodStatus', svc);
                return evt.promise.then(function (response) {
                    return response;
                });
            }
        },
        delReplicationController:function(){
            var data = {

            }
            return $http.post('/apik8s/modifyRc', data).then(function (response) {
                return response;
            });
        },
        createService:function(data,evt){
            if(evt !== undefined){
                evt.promise = $http.post('/apiApplication/createApplication', data );
                return evt.promise.then(function (response) {
                    return response;
                });
            }


        },
        deleteService: function (data,isDelVolume) {
            var _postData = {
                svc:data,
                isDelVolume:isDelVolume
            }
            return $http.post('/apiApplication/deleteApplication', _postData).then(function (response) {
                if( response && response.data){
                    var result = response.data ;
                    if( result.ret ){
                        result.status =  result.status||200 ;
                        return result ;
                    }
                    throw result ;
                }
                return response;
            });
        },
        getServices: function (serviceName,clusterId) {
            var url = '/apiApplication/getApplications';
            if (clusterId)
                url += "?clusterId=" + clusterId;
            else
                url += "?clusterId=default";
            if (serviceName && serviceName!== undefined)
                url += "&servicename=" + serviceName;

            return $http.get(url).then(function (response) {
                if( response && response.data){
                    var result = response.data ;
                    if( result.ret ){
                        result.status =  result.status||200 ;
                        return result ;
                    }
                    throw result ;
                }
                return response;
            });
        },
        updateService:function(oldSvc,newSvc,evt){
            var data = {
                oldsvc:oldSvc,
                newsvc:newSvc
            }
            evt.promise = $http.post('/apiApplication/updateApplication', data);
            return evt.promise.then(function (response) {
                if( response && response.data ){
                    var result = response.data ;
                    if( result.ret ){
                        result.status =  result.status||200 ;
                        return result ;
                    }
                    throw result ;
                }
                return response;
            });
        },
        getPodLog: function (instanceName,clusterId,sinceTime) {
            if(clusterId === undefined)
                clusterId = 'default';
            var url = '';
            if (sinceTime === undefined){
                url = '/apiApplication/getPodLog?clusterId='+clusterId+'&instancename=' +  instanceName;
            }else{
                var url = '/apiApplication/getPodLog?clusterId='+clusterId+'&instancename=' +  instanceName + '&sinceTime=' + sinceTime;
            }
            return $http.get(url).then(function (response) {
                return response;
            });
        },
        getPodEvents: function (instanceName,clusterId) {
            if(clusterId === undefined)
                clusterId = 'default';
            var url = '/apiApplication/getEvents?clusterId='+clusterId+'&instancename=' +  instanceName;
            return $http.get(url).then(function (response) {
                if(response && response.data){
                    //only need the  data returned
                    response.status =  response.status||200 ;
                    return response.data ;
                }else{
                    return response;
                }
            });
        },
        updateServiceStatus:function(svc,status){
            var data = {
                //app:svc.app,
                svc:svc,
                status:status
            }
            return $http.post('/apiApplication/updateAppStatus', data).then(function (response) {
                if( response && response.data ){
                    var result = response.data ;
                    if( result.ret ){
                        result.status =  result.status||200 ;
                        return result ;
                    }
                    throw result ;
                }
                return response;
            });
        },
        Autoupdate:function(svc,status){
            var data={
                svc:svc,
                autoStatus:status
            }
            return $http.post('/apiApplication/updateAutoStatus', data).then(function (response) {
                if( response && response.data ){
                    var result = response.data ;
                    if( result.ret ){
                        result.status =  result.status||200 ;
                        return result ;
                    }
                    throw result ;
                }
                return response;
            });
        },
        checkIfResExceedLimit:function(svc,status,scale_num,op){
            //检查是否超过资源配额
            // response:{
            //     "data" : true,   //if the resource is enough
            //     "status" : 200,
            //     "statusText" : "OK"
            // }
            var data = {
                data:svc ,
                status:status,
                replicas:scale_num,
                op: op
            }
            return $http.post('/apiApplication/checkResourceQuotas', data).then(function (response) {
                if( response && response.data ){
                    var result = response.data;
                    if( result.ret ){
                        result.status =  result.status||200 ;
                        return result ;
                    }
                    throw result ;
                }
                return response;
            });
        },
        //pod auto scale operations -start-
        createPodAutoScale: function (autoScalerEntity,clusterId,params,status) {
            autoScalerEntity = autoScalerEntity||{} ;
            //autoScalerEntity = {
            //     scaleName : "scale-test",
            //     max : 2,
            //     min : 1 ,
            //     refKind : "ReplicationController",
            //     refName : "node4-test-v2.0.4.1",
            //     cpuPct : 80
            // }
            var data={
                svc:params.data,
                max:autoScalerEntity.max,
                cpu:autoScalerEntity.cpuPct,
                scalerEnabled:status
            }

            autoScalerEntity["clusterId"] = clusterId ;
            return $http.post('/apiApplication/createPodAutoScale', autoScalerEntity).then(function (response) {
                if( response && response.data ){
                    var result = response.data ;
                    if( result.ret ){
                        result.status =  result.status||200 ;
                        if(result.status==200){
                            return $http.post('/apiApplication/updateScaleStatus', data).then(function (respons) {
                            var resul=respons.data;
                            if(resul.ret){
                                resul.status =  resul.status||200 ;
                                return resul ;
                            }
                            })
                        }
                        return result ;
                    }
                    throw result ;
                }
                return response;
            });
        },
        replacePodAutoScale: function (autoScalerEntity,clusterId) {
            autoScalerEntity = autoScalerEntity||{} ;
            //给个栗子，应该传的参数如下：
            //autoScalerEntity = {
            //     scaleName : "scale-test",
            //     max : 2,
            //     min : 1 ,
            //     refKind : "ReplicationController",
            //     refName : "node4-test-v2.0.4.1",
            //     cpuPct : 80
            // }
            autoScalerEntity["clusterId"] = clusterId ;
            return $http.post('/apiApplication/replaceAutoScale', autoScalerEntity).then(function (response) {
                if( response && response.data ){
                    var result = response.data ;
                    if( result.ret ){
                        result.status =  result.status||200 ;
                        return result ;
                    }
                    throw result ;
                }
                return response;
            });
        },
        deletePodAutoScale: function (autoScalerEntity,clusterId,params) {
            autoScalerEntity = autoScalerEntity||{} ;
            var scaleName = autoScalerEntity.scaleName ||"";
            var url = '/apiApplication/deletePodAutoScale?clusterId=';
            clusterId = clusterId||"" ;
            url+= clusterId ;
            url+= '&scaleName='+scaleName ;
            var data={
                svc:params.data,
                max:5,
                cpu:5,
                scalerEnabled:false
            }
            return $http.get(url).then(function (response) {
                if( response && response.data){
                    var result = response.data ;
                    if( result.ret ){
                        result.status =  result.status||200 ;
                        if(result.status==200){
                            return $http.post('/apiApplication/updateScaleStatus', data).then(function (respons) {
                                var resul=respons.data;
                                if(resul.ret){
                                    resul.status =  resul.status||200 ;
                                    return resul ;
                                }
                            })
                        }
                        return result ;
                    }
                    throw result ;
                }
                return response;
            });
        },
        deleteAllPodAutoScale: function (autoScalerEntity,clusterId) {
            autoScalerEntity = autoScalerEntity||{} ;
            var scaleName = autoScalerEntity.scaleName ||"";
            var url = '/apiApplication/deleteAllPodAutoScale?clusterId=';
            clusterId = clusterId||"" ;
            url+= clusterId ;
            url+= '&scaleName='+scaleName ;

            return $http.get(url).then(function (response) {
                if( response && response.data){
                    var result = response.data ;
                    if( result.ret ){
                        result.status =  result.status||200 ;
                        return result ;
                    }
                    throw result ;
                }
                return response;
            });
        },
        listPodAutoScale: function (autoScalerEntity,clusterId) {
            autoScalerEntity = autoScalerEntity||{} ;
            var scaleName = autoScalerEntity.scaleName ||"";
            var url = '/apiApplication/listPodAutoScale?clusterId=';
            clusterId = clusterId||"" ;
            url+= clusterId ;
            url+= '&scaleName='+scaleName ;

            return $http.get(url).then(function (response) {
                if( response && response.data){
                    var result = response.data ;
                    if( result.ret ){
                        result.status =  result.status||200 ;
                        return result ;
                    }
                    throw result ;
                }
                return response;
            });
        },
        findPodAutoScale: function (autoScalerEntity,clusterId) {
            autoScalerEntity = autoScalerEntity||{} ;
            var scaleName = autoScalerEntity.scaleName ||"";
            var url = '/apiApplication/findPodAutoScale?clusterId=';
            clusterId = clusterId||"" ;
            url+= clusterId ;
            url+= '&scaleName='+scaleName ;

            return $http.get(url).then(function (response) {
                if( response && response.data){
                    var result = response.data ;
                    if( result.ret ){
                        result.status =  result.status||200 ;
                        return result ;
                    }
                    throw result ;
                }
                return response;
            });
        }
        //pod auto-scale -end-
        ,publishTestVersionRc: function (clusterId,app) {
            return new Promise(function(resolve,reject){
                var req={
                    app:app,
                    clusterId:clusterId
                }
                console.log(req)
                $http.post('/apiApplication/publishTestVersionRc',req).then(function (response) {
                    resolve(response);
                });
            });

        }
        ,deleteTestVersionForSvc: function (clusterId,app) {
            return new Promise(function(resolve,reject){
                var req={
                    app:app,
                    clusterId:clusterId
                }
                console.log(req)
                $http.post('/apiApplication/deleteTestVersionRc',req).then(function (response) {
                    resolve(response);
                });
            }).then(function(val){
                console.log(val);
            });

        }
        ,addTestVersionForSvc: function (clusterId,app,ver,testVer) {
            return new Promise(function(resolve){
                $http.post('/apiApplication/getRc', {
                    app:app,
                    ver:ver,
                    node:{
                        clusterId:clusterId
                    }
                }).then(function (response) {
                    var res=response.data.items;
                    if(!res||res.length<=0){

                    }else {
                        resolve(res.shift())
                    }
                });
            }).then(function(val){
                var app=val.metadata.labels.app;
                var name=app+"-v"+testVer;
                var stableVer=val.metadata.labels.version;
                var spec=val.spec;
                var stableImage=spec.template.spec.containers[0].image;
                var labels={
                    app:app,
                    version:testVer
                };
                spec.selector=labels;
                spec.template.metadata.labels=labels;
                spec.template.spec.containers[0].image=stableImage.replace(stableVer,testVer);
                var req={
                    testVersion:testVer,
                    app:app,
                    clusterId:clusterId,
                    rc:{
                        apiVersion: "v1",
                            kind:"ReplicationController",
                        metadata:{
                        name:name,
                            namespace:val.metadata.namespace,
                            labels:labels
                    },
                        spec:spec
                    }
                }
                //console.log(req)
                return new Promise(function(resolve,reject){
                    $http.post('/apiApplication/addTestVersionRc',req).then(function (response) {
                        resolve(response);
                    });
                });
            });

        }
    };
});